package ext.tianma.part.copybom.validators;

import com.ptc.core.ui.validation.DefaultUIComponentValidator;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationResult;
import com.ptc.core.ui.validation.UIValidationResultSet;
import com.ptc.core.ui.validation.UIValidationStatus;

import ext.com.core.CoreUtil;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;

import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTReference;
import wt.inf.container.WTContainer;
import wt.inf.team.ContainerTeam;
import wt.inf.team.ContainerTeamManaged;
import wt.inf.team.ContainerTeamManagedInfo;
import wt.inf.team.ContainerTeamReference;
import wt.lifecycle.LifeCycleManaged;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.part.WTPartUsageLink;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.Workable;

/**
 * 复制Bom入口验证
 * @author zengchen
 *
 */
public class CopyBomValidator extends DefaultUIComponentValidator {
	@SuppressWarnings("deprecation")
	public UIValidationResultSet performFullPreValidation(
			UIValidationKey validationkey,
			UIValidationCriteria validationcriteria, Locale locale)
			throws WTException {
		UIValidationResultSet resultSet = new UIValidationResultSet();
		WTReference wtreference = validationcriteria.getContextObject();
		if (wtreference == null) {
			resultSet.addResult(new UIValidationResult(validationkey,
					UIValidationStatus.HIDDEN));
			return resultSet;
		}
		Persistable persistable = wtreference.getObject();
		String view = "";
		if ((persistable instanceof WTPart)) {
			WTPart part = (WTPart) persistable;
			view = part.getViewName();
			
			//检出隐藏
			Workable workble = (Workable) persistable;
			if (WorkInProgressHelper.isCheckedOut(workble)) {
				resultSet.addResult(new UIValidationResult(validationkey,
						UIValidationStatus.HIDDEN));
				return resultSet;
			}
			
			//有子件的隐藏
			Vector<WTPartUsageLink> partlinks = CoreUtil.getPartUsageLinks(part);
			if(partlinks != null && partlinks.size() > 0 ){
				resultSet.addResult(new UIValidationResult(validationkey,
						UIValidationStatus.HIDDEN));
				return resultSet;
			}
			
			//设计视图的隐藏
			if ("Design".equals(view)) {
				resultSet.addResult(new UIValidationResult(validationkey,
						UIValidationStatus.HIDDEN));
				return resultSet;
			}
			
			//用户角色非BOM工程师或者系统管理员的隐藏
			Boolean flag = true;
			WTPrincipal  principal = SessionHelper.manager.getPrincipal();
			Role role=Role.toRole("BOMEngineer");
			ArrayList userList=getAllPrincipalsForTarget(part.getContainer(), role);
			if(null!=userList){
		    	   for(int i=0;i<userList.size();i++){
				       WTPrincipalReference reference=(WTPrincipalReference)userList.get(i);
				       WTPrincipal principal1=reference.getPrincipal();
				       if(principal==principal1){                  		
				            flag = false;
				          	break;
				       } 							
				       if(principal1 instanceof WTGroup) {
							WTGroup group=(WTGroup)principal1;
							Enumeration member = group.members();
							while (member!=null&&member.hasMoreElements()) {
							WTPrincipal prinUser = (WTPrincipal) member.nextElement();
								if(prinUser==principal){                  		
						          		flag = false;
						          		break;
						         }
							}
						}			          	
		            }
		    }
			//与正式环境的class文件有差异
			WTGroup siteAdmin = getGroupByName("Administrators");
			if(siteAdmin.isMember(principal)){
				flag = false;
			}
			if(flag){
				resultSet.addResult(new UIValidationResult(validationkey,
						UIValidationStatus.HIDDEN));
				return resultSet;
			}
			
			//部件状态非正在工作的隐藏
			LifeCycleManaged lcm = (LifeCycleManaged) part;
			if (!"INWORK".equals(lcm.getLifeCycleState().toString())) {
				resultSet.addResult(new UIValidationResult(validationkey,
						UIValidationStatus.HIDDEN));
				return resultSet;
			}

		}

		resultSet.addResult(UIValidationResult.newInstance(validationkey,
				UIValidationStatus.ENABLED));
		return resultSet;
	}
	
	 /**
     * 得到容器中该角色下的所有用户
     * @param container
     * @param role
     * @return ArrayList
     * @throws WTException
     */
    @SuppressWarnings("rawtypes")
	public static ArrayList getAllPrincipalsForTarget(WTContainer container, Role role)
    throws WTException{
    if (((container instanceof ContainerTeamManaged)) && (role != null)) {
      ContainerTeamManaged ctm = (ContainerTeamManaged)container;
      ContainerTeamManagedInfo containerteammanagedinfo = ctm.getContainerTeamManagedInfo();
      ContainerTeam containerTeam = wt.inf.team.ContainerTeamHelper.service.getContainerTeam(ctm);
      if ((containerteammanagedinfo.getSharedTeamId() != null) && (containerteammanagedinfo.getSharedTeamId().getKey() != null) && 
        (containerteammanagedinfo.getSharedTeamId().getKey().getClassname() != null))
      {
        ArrayList localWtps = containerTeam.getAllPrincipalsForTarget(role);
        
        ArrayList allWtps = localWtps;
        ContainerTeamReference containerTeamRef = ctm.getSharedTeamReference();
        if (containerTeamRef != null) {
          ContainerTeam sharedTeam = (ContainerTeam)containerTeamRef.getObject();
          if (sharedTeam != null) {
            ArrayList sharedWtps = sharedTeam.getAllPrincipalsForTarget(role);
            
            for (int i = 0; i < sharedWtps.size(); i++) {
              WTPrincipalReference wtpRef = (WTPrincipalReference)sharedWtps.get(i);
              if (!allWtps.contains(wtpRef)) {
                allWtps.add(wtpRef);
              }
            }
          }
        }
        return allWtps;
      }
      
      return containerTeam.getAllPrincipalsForTarget(role);
    }     
    return null;
  }
    
	/**
	 * 根据名称获取部门组
	 * @param name 组名称
	 * @return WTGroup
	 * @throws WTException the WTException
	 */
	@SuppressWarnings("deprecation")
	public static WTGroup getGroupByName(String name) throws WTException {
		QuerySpec qs=null;
		QueryResult qr=null;
		qs= new QuerySpec(WTGroup.class);
		//根据组名称查询
		SearchCondition sc = new SearchCondition(WTGroup.class, "name", SearchCondition.EQUAL, name);
		qs.appendSearchCondition(sc);
		//根据组的类型过滤
		SearchCondition sc2 = new SearchCondition(WTGroup.class, "internal", SearchCondition.IS_FALSE);
		qs.appendAnd();
		qs.appendSearchCondition(sc2);
		qr = PersistenceHelper.manager.find(qs);
		WTGroup group=null;
		if(qr.hasMoreElements())
			group= (WTGroup)qr.nextElement();

		return group;
	}
}